//
//  ST_BTMessageController.swift
//  BTVideo
//
//  Created by DouLei on 2019/7/10.
//  Copyright © 2019 DouLei. All rights reserved.
//

import UIKit
import SnapKit
import SwiftyJSON
import SwifterSwift
import NIMSDK
import UserNotifications
import SwiftyUserDefaults
import RealmSwift
//import DifferenceKit
import RxSwift
import RxCocoa




var LIKE_NUMBER_PLUS_OFFSET = 0

//MARK: -
class ST_BTMessageController: UIViewController {
    
    //    MARK: - Life Cycle
    //    static let shared = ST_BTMessageController()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
         
        
        self.view.backgroundColor = Color.white
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.top.left.right.bottom.equalTo(view)
        }
        
        view.addSubview(right_bottom_banner)
        right_bottom_banner.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-17)
            make.bottom.equalToSuperview().offset(-81-75-BTSafeAreaBottom)
            make.width.equalTo(82)
            make.height.equalTo(80+10)
        }
        
        check_authorisation()
        
        binding()
        
    }
    
    
    //    MARK: - Properties
    
    fileprivate lazy var authority_controller:ST_NotificationAuthorityController = {
        return ST_NotificationAuthorityController()
    }()
    
    fileprivate lazy var right_bottom_banner:ST_MsgRightBottomBanner = {
       let v =  ST_MsgRightBottomBanner()
        v.alpha = 0
        return v
    }()
    
    fileprivate lazy var titleLabel:UILabel = {
        let control = UILabel.init()
        control.text = "消息"
        control.textColor = Color.black
        control.font = UIFont.systemFont(ofSize: 24, weight: UIFont.Weight.medium)
        return control
    }()
    
    fileprivate lazy var tableView:UITableView = {
        
        let control = UITableView.init(frame: CGRect.zero, style: UITableView.Style.plain)
        
        control.delegate = self
        //        control.dataSource = self
        control.showsVerticalScrollIndicator = false
        
        control.register(cellWithClass: ST_ConversationListCell.self)
        
        control.separatorStyle = .none
        
        control.backgroundColor = Color.white
        
        //        control.backgroundColor = Color.random
        
        control.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: 52+BTSafeAreaBottom, right: 0)
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        return control
    }()
    
    
    //    fileprivate lazy var guidance_header:ST_MsgPeculiarityGuidanceHeader = {
    //        let control = ST_MsgPeculiarityGuidanceHeader()
    //        control.edit_closure = {[weak self] in
    //
    //            push_to_push_peculiarity_controller(navigationController: self?.navigationController)
    //        }
    //           return control
    //       }()
    
    fileprivate lazy var bannerHeader:ST_MsgBannerHeader = {
        let l = ST_MsgBannerHeader()
        return l
    }()
    
    var disposeBag = DisposeBag()
    
    fileprivate var bannerObserver = PublishSubject<[ST_MsgBannerHeaderCellModel]>()
    
    fileprivate var right_bottom_banner_observer = PublishSubject<[ST_MsgBannerHeaderCellModel]>()
    
    fileprivate lazy var adapter = ST_ConversationAdapter.shared
}

extension ST_BTMessageController:UITableViewDelegate{
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return ST_ConversationListCell.height
    }
    
    /*
     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
     
     return adapter.sessionList.count
     }
     
     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
     
     let cell = tableView.dequeueReusableCell(withClass: ST_ConversationListCell.self)
     
     //        if let m = adapter.sessionList[safe:indexPath.row]{
     //            cell.setUp(model: m)
     //        }
     
     return cell
     }*/
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        guard let model = adapter.sessionList[safe:indexPath.row],let iCell = cell as? ST_ConversationListCell else{
            return
        }
        
        iCell.bind(model: model)
        
    }
    
    
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if self.navigationController?.topViewController is ST_PrivateChatViewController{
            
            print("连续点击-----")
            
            return
        }
        
        
        guard let m = adapter.sessionList[safe:indexPath.row] else{ return }
        
        ST_ConversationAdapter.shared.mark_read(sessionId: m.sessionId)
        
        switch m.sessionId {
            
        case LOVE_ASSISTANT_SESSION_ID:
            
            //            男的 不是会员 加蒙层
            if FETCH_MEMBER_STATUS() != .subscribe && ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == .male {
                
                popup_membership_controller()
                
                return
            }
            
            let vc = ST_ReceiveLoveModuleController()
            
            self.navigationController?.pushViewController(vc)
            //            特质 收到的点赞
        case PECULIARITY_ASSISTANT_SESSION_ID:
            
            let vc = ST_ReceiveThumbUpByEmojiController()
            
            self.navigationController?.pushViewController(vc)
            //            收到的关注
        case FOLLOW_ASSISTANT_SESSION_ID:
            
            let vc = ST_ReceiveFollowViewController()
            
            self.navigationController?.pushViewController(vc)
            //            收到的评论
        case COMMENT_ASSISTANT_SESSION_ID:
            
            let vc = ST_ReceiveCommentsViewController()
            
            self.navigationController?.pushViewController(vc)

            //            小助手跳转新需求
        case DIALOGUE_ASSISTANT_SESSION_ID:
            
            let vc = ST_QuestionHomeViewController()
            
            self.navigationController?.pushViewController(vc)
            
        default:
            
            
            //            push_to_chat_controller(info: ST_ChatInfoStruct.init(sessionId: m.sessionId, title: m.userName, source: "聊天列表",intimacyImage:m.sweetValueImage), navigationController: self.navigationController)
            /// 不是小助手，才验证手机号绑定
            if ASSISTANT_SET.contains(m.sessionId) == false , BTVerticalAlertViewController.toastBindPhoneRequireAlert(fromController: self) {
                return
            }
            
            
            let provider = BINP
            
            guard let info = try? provider.storage?.object(forKey: m.sessionId) else{
                return
            }
            
            let vc = ST_PrivateChatViewController()
            
            vc.sessionID = m.sessionId
            //
            vc.intimacyImage = info.sweetValueImage
            
            vc.source = "聊天列表"
            
            self.navigationController?.pushViewController(vc)
            
        }
        
        
        
        
    }
    
    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        
        return nil
    }
    
}

extension ST_BTMessageController{
    
    private func setup_authority_controller(){
        
        self.addChild(authority_controller)
        view.addSubview(authority_controller.view)
        
        var edge = UIEdgeInsets.zero
        if !iPhoneXSeries{
            edge = UIEdgeInsets.init(top: -70, left: 0, bottom: 70, right: 0)
        }
        
        authority_controller.view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(edge)
        }
        
    }
    
    fileprivate func check_authorisation(){
        
        UNUserNotificationCenter.current().getNotificationSettings { (settings) in
            
            if settings.authorizationStatus == .notDetermined{
                
                main_thread_execute {
                    
                    self.setup_authority_controller()
                }
                
            }
        }
    }
    
    
    fileprivate func binding(){
        
        bannerObserver.subscribe(onNext: {[weak self] list in
            
            self?.bannerHeader.data_array = list
            
            if list.count > 0 {
                
                self?.bannerHeader.frame = CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: ScreenWidth, height: TIANCompatibleValue(value: 80)))
                
                self?.tableView.tableHeaderView = self?.bannerHeader
                
            }else{
                
                self?.tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: CGFloat.leastNonzeroMagnitude))
                
                //            self.tableView.layoutIfNeeded()
            }
            
        }).disposed(by: disposeBag)
        
        right_bottom_banner_observer.withUnretained(self).subscribe(onNext: { own, list in
            
            if list.count > 0 {
                own.right_bottom_banner.data_array = list
                own.right_bottom_banner.alpha = 1
            }else{
                own.right_bottom_banner.alpha = 0
            }
            
        }).disposed(by: disposeBag)
        
        
        
        adapter.recent_session_observer.bind(to: tableView.rx.items(cellIdentifier: String(describing: ST_ConversationListCell.self))) { index, model, cell in
            
            guard let iCell = cell as? ST_ConversationListCell else{
                return
            }
            
            iCell.bind(model: model)
        }
        .disposed(by: disposeBag)
        
        BINP.update_displaying_subject.debounce(RxTimeInterval.seconds(1), scheduler: MainScheduler.instance).subscribe(onNext: {[weak self] in
            
            self?.update_displaying_cells_data()
            
        }).disposed(by: disposeBag)
        
        SCComponets.login_status_did_changed_observable().distinctUntilChanged().withUnretained(self).subscribe(onNext: { own,f in
            print("SCComponets.login_status_did_changed_observable()")
            if f == true{
                own.fetchBanner()
            }else{
                own.bannerObserver.onNext([])
            }
            
        }).disposed(by: rx.disposeBag)
        
        
    }
    
    fileprivate func update_displaying_cells_data() {
        
        guard let array = tableView.indexPathsForVisibleRows else { return  }
        
        for indexPath in array{
            
            guard let model = adapter.sessionList[safe:indexPath.row],let iCell = tableView.cellForRow(at: indexPath) as? ST_ConversationListCell else{
                continue
            }
            
            iCell.bind(model: model)
        }
        
    }
    
    fileprivate func fetchBanner(){
        
        JVrequest(PH.fetchBannerApi) { json in
            
            let list = json["data"].arrayValue.map({ ST_MsgBannerHeaderCellModel(fromJson: $0) })
            
            self.bannerObserver.onNext(list)
            
        } failure: { code, errr in
            
        }
        
        
        JVrequest(PH.fetchBannerApi,parameters: ["location":2]) { json in
            
            let list = json["data"].arrayValue.map({ ST_MsgBannerHeaderCellModel(fromJson: $0) })
            
            self.right_bottom_banner_observer.onNext(list)
            
        } failure: { code, errr in
            
        }
    }
    
    
    
    @objc fileprivate func popup_membership_controller(){
        
        ST_MaidWayManager.shared.source = .遇见_喜欢了我
        
        
        let vc  = ST_MemberSubscriberController.init(subscribeType: ST_BitianSubscribeType.查看谁喜欢我)
        
        vc.overCurrentContext = true
        
        GlobalPresent(toController: vc, animated: false)
    }
}

extension ST_BTMessageController{
    
    func clear_recent_sessions_handle(){
        
        let alert = BTVerticalAlertViewController.clearAllRecentSessionsAlert()
        
        
        alert.confirm_closure = {[weak self] in
            
            self?.adapter.clear_recent_sessions()
        }
        
    }
    
    
    
}

/*
 extension ST_BTMessageController:ST_ConversationAdapterUIUpdateDelegate{
 
 
 
 func reload(using stagedChangeset: StagedChangeset<[ST_TianSessionSummaryStruct]>, setData: ([ST_TianSessionSummaryStruct]) -> Void) {
 
 tableView.reload(using: stagedChangeset, with: UITableView.RowAnimation.none, setData: setData)
 
 }
 
 func updateCellData(sessionData: ST_TianSessionSummaryStruct) {
 
 guard let cell = tableView.visibleCells.first(where: { ($0 as? ST_ConversationListCell)?.sessionModel?.sessionId == sessionData.sessionId }) as? ST_ConversationListCell  else{
 return
 }
 
 cell.bind(model: sessionData)
 
 }
 
 
 
 
 func refresh_all_data() {
 self.tableView.reloadData()
 }
 }
 */
